package service

import (
	"admin100/app/model"
	"context"
	"github.com/gogf/gf/net/ghttp"
)

var Context = &ContextService{}

type ContextService struct {
}

const ContextKey = "ns_context_key"

func (s *ContextService) Init(r *ghttp.Request, ctxContext *model.Context) {
	r.SetCtxVar(ContextKey, ctxContext)
}

func (s *ContextService) Get(ctx context.Context) *model.Context {
	value := ctx.Value(ContextKey)
	if value == nil {
		return nil
	}
	if localCtx, ok := value.(*model.Context); ok {
		return localCtx
	}
	return nil
}

func (s *ContextService) Set(ctx context.Context, cxtUser *model.MyadminUser) {
	s.Get(ctx).User = cxtUser
}

func (s *ContextService) GetUser(ctx context.Context) *model.MyadminUser {
	customCtx := s.Get(ctx)
	if customCtx != nil && customCtx.User != nil {
		return customCtx.User
	}

	return nil
}
